package cn.sell.filter;//package net.iyutong.common.filter;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;

/**
  *@Author: Limi
  *@Contact : qq(2393839633),Email(13924223985@163.com)
  *@Description: TODO: 处理请求体工具类
  *@Date: 2020/4/3 14:41
  *@Version: 1.0
  **/
public class HttpHelper {

    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取请求报文
     */
    public static String getReqStr(ServletRequest requestWrapper) throws IOException {
        InputStream is = requestWrapper.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] bytes = null;
        if(null != is){
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            bytes = outSteam.toByteArray();
        }
        String xml = new String(bytes, "UTF-8");
        outSteam.close();
        is.close();
        return xml;
    }

//    public static String getResStr(ServletResponse responseWrapper) throws IOException {
//        ServletOutputStream os = responseWrapper.getOutputStream();
//
//        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len = -1;
//        while ((len = outSteam.read(buffer)) != -1) {
//            outSteam.write(buffer, 0, len);
//        }
//        byte[] bytes = outSteam.toByteArray();
//        String xml = new String(bytes, "UTF-8");
//        outSteam.close();
//        is.close();
//        return xml;
//    }
}